package com.it.controller;

import com.it.entity.User;
import com.it.service.DataFetchService;
import com.it.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户控制层
 *
 * @author hua
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {
    private final UserService userService;

    @Autowired
    private DataFetchService dataFetchService;

    public UserController (UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/saveUser")
    public User saveUser(@RequestBody User user) {
        return userService.insert(user);
    }

    @GetMapping(value = "/{userId}")
    public ResponseEntity<User> getUser(@PathVariable Integer userId) {
        User user = userService.findUser(userId);
        HttpStatus status = user == null ? HttpStatus.NOT_FOUND: HttpStatus.OK;
        return new ResponseEntity<>(user, status);
    }

    @GetMapping(value = "/getUserSelfKey/{userId}")
    public ResponseEntity<User> getUserSelfKey(@PathVariable Integer userId) {
        User user = userService.findUserSelfKey(userId);
        HttpStatus status = user == null ? HttpStatus.NOT_FOUND: HttpStatus.OK;
        return new ResponseEntity<>(user, status);
    }

    @DeleteMapping(value = "/{userId}")
    public ResponseEntity deleteUser(@PathVariable Integer userId) {
        userService.delete(userId);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @GetMapping(value = "/getBatchUser")
    public ResponseEntity<List<User>> getBatchUser() {
        List<User> users = dataFetchService.dataFetchTask();
        HttpStatus status = users == null ? HttpStatus.NOT_FOUND: HttpStatus.OK;
        return new ResponseEntity<>(users, status);
    }
}